from django import http
from django.core.cache import cache
from django.views import View

from areas.models import Area
from response_code import RET
from response_code import RET


class Areas(object):
    pass


class AreasView(View):
    def get(self,request):
        area_id = request.GET.get('area_id')
        if not area_id:
            #取缓存数据
            p_list=cache.get('province_list')
            if not p_list:
                # 获取省份数据
                '''{"code": "0",
                   "errmsg": "OK",
                   "province_list": [
                   {
                    "id": 110000,
                    "name": "北京市"},
                }'''
                provinces=Area.objects.filter(parent__isnull=True)
                p_list=[]
                for p in provinces:
                    p_data={'id':p.id,'name':p.name}
                    p_list.append(p_data)
                cache.set('province_list',p_list,300)
            else:
                pass
            res = {
                'code': '0',
                'errmsg': 'OK',
                'province_list': p_list,
            }
            return http.JsonResponse(res)

        # 获取市区数据
        else:
            sub_data=cache.get('sub_data_%s'% area_id)
            if not sub_data:
                try:
                    area=Area.objects.get(id=area_id)
                except Exception as e:
                    return http.JsonResponse({'code':RET.PARAMERR,'errmsg':'区域id错误'})
                area_subs=area.subs.all()
                # '''{"code": "0",
                # "errmsg": "OK",
                # "sub_data": {
                # "id": 130000,
                # "name": "河北省",
                # "subs": [{
                #         "id": 130100,
                #         "name": "石家庄市"},
                #         .....]
                #     }
                # }'''
                subs=[]
                for a in area_subs:
                    area_data={'id':a.id,'name':a.name}
                    subs.append(area_data)
                sub_data={
                    'id':area.id,
                    'name':area.name,
                    'subs':subs
                }
                cache.set('sub_data_%s'% area_id,sub_data,3600)
            else:
                pass
            res={
                'code': '0',
                'errmsg': 'OK',
                'sub_data': sub_data
            }
            return http.JsonResponse(res)




